package cn.xyy.common.file;

import org.apache.commons.lang3.StringUtils;

import cn.xyy.common.spring.SpringMVCUtil;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

/**
 * 文件处理工具类
 * 
 * @author xyy
 *
 */

public class FileUtils extends org.apache.commons.io.FileUtils {

	public static void download(final String path) throws IOException {
		if (StringUtils.isBlank(path)) {
			throw new IOException("path '" + path + "' is  empaty");
		}
		File file = new File(path);
		byte[] bytes = readFileToByteArray(file);
		HttpServletResponse response = SpringMVCUtil.getResponse();
		OutputStream out = response.getOutputStream();
		out.write(bytes);
		out.flush();
		out.close();
	}

	public static File upload(final byte[] data, final String path) throws IOException {
		if (StringUtils.isBlank(path)) {
			throw new IOException("path '" + path + "' is  empaty");
		}
		// 创建文件路径
		File dest = new File(path);
		// 判断文件是否已经存在
		if (dest.exists()) {
			throw new IOException("File '" + dest + "'exists");
		}
		// 判断文件父目录是否存在
		if (!dest.getParentFile().exists()) {
			dest.getParentFile().mkdir();
		}
		FileUtils.writeByteArrayToFile(dest, data);
		return dest;
	}

	public static void checkSize(long maxSize, long size) throws IOException {
		// 1M
		int len = 1024 * 1024;
		if (size > (maxSize * len)) {
			throw new IOException("文件超出规定大小:" + maxSize + "MB");
		}
	}

	/**
	 * 获取文件扩展名，不带 .
	 */
	public static String getExtensionName(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length() - 1))) {
				return filename.substring(dot + 1);
			}
		}
		return filename;
	}

	/**
	 * 获取不带扩展名的文件名
	 */
	public static String getFileNameNoEx(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length()))) {
				return filename.substring(0, dot);
			}
		}
		return filename;
	}

}
